package studio.raptor.databus.dashboard.service.impl;

import java.sql.Timestamp;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import studio.raptor.databus.dashboard.common.Constants;
import studio.raptor.databus.dashboard.repository.AppCenter;
import studio.raptor.databus.dashboard.repository.AppCenterRepository;
import studio.raptor.databus.dashboard.service.interfaces.AppCenterService;
import studio.raptor.databus.dashboard.service.interfaces.MessageByLocaleService;

/**
 * @author Sam
 * @since 3.1.0
 */
@Service
public class AppCenterServiceImpl implements AppCenterService {

  private AppCenterRepository appCenterRepository;
  private MessageByLocaleService messageByLocaleService;

  @Autowired
  public AppCenterServiceImpl(AppCenterRepository appCenterRepository,
      MessageByLocaleService messageByLocaleService) {
    this.appCenterRepository = appCenterRepository;
    this.messageByLocaleService = messageByLocaleService;
  }

  @Override
  public List<AppCenter> getAllAppCenter() {
    return appCenterRepository.findAllByStatusEqualsOrderByIdAsc(Constants.STATUS_VALID);
  }

  @Override
  public Page<AppCenter> getAppCenter(Integer page, Integer count) {
    Pageable pageable = new PageRequest(page, count, Direction.DESC, "id");
    return appCenterRepository.findByStatus(Constants.STATUS_VALID, pageable);
  }

  @Override
  public List<AppCenter> getAppCenterByName(String name) {
    return appCenterRepository.findByNameContainingAndStatusEquals(name, Constants.STATUS_VALID);
  }

  @Override
  public List<AppCenter> getAppCenterByCode(String code) {
    return appCenterRepository.findByCode(code);
  }

  @Transactional
  @Override
  public AppCenter createAppCenter(String centerName, String centerCode, String desc) {
    // check center code exists
    List<AppCenter> appCenters = appCenterRepository.findByCode(centerCode);
    if (null != appCenters && !appCenters.isEmpty()) {
      throw new RuntimeException(
          messageByLocaleService.getMessage("center_already_exist", new Object[]{centerCode}));
    }
    AppCenter ac = new AppCenter();
    ac.setName(centerName);
    ac.setCode(centerCode);
    ac.setDescription(desc);
    ac.setRegisterTime(new Timestamp(System.currentTimeMillis()));
    ac.setStatus(Constants.STATUS_VALID);
    appCenterRepository.save(ac);
    return ac;
  }

  @Transactional
  @Override
  public void deleteAppCenter(Long id) {
    appCenterRepository.softDelete(id);
  }
}
